# 查看 SQL 历史和执行画像

从工作区 SQL 执行历史取得语句标识，再读取执行详情和画像。

(sdk-ai-studio-sql-history-prepare)=
## 准备

1. [配置 SDK 和个人访问令牌](../../../quickstart/ai-studio/sdk.md#sdk-ai-studio-quickstart-configure)。
2. [选择工作区并获取工作区 ID](../../../quickstart/ai-studio/sdk.md#sdk-ai-studio-quickstart-workspaces)。


(sdk-ai-studio-sql-history-s1)=
(sdk-ai-studio-sql-history-action-2)=
## 查询历史并读取画像

示例查询最近 20 条执行记录，并读取首条记录的详情与画像。

:::::{tab-set}
:sync-group: sdk-language

::::{tab-item} Python
:sync: python

```python
import os

import moi_product_sdk as sdk

client = sdk.new_with_personal_access_token(
    os.environ["PRODUCT_API_BASE_URL"], os.environ["PRODUCT_API_KEY"]
)
workspace_id = os.environ["WORKSPACE_ID"]
workspace = client.workspace(workspace_id)
service = workspace.sql()
page = service.query_history(sdk.with_query_history_offset(0), sdk.with_query_history_limit(20))
print("总数:", page.total, "偏移:", page.offset, "数量:", page.limit)
for record in page.query_list:
    print(record.statement_id, record.database, record.status, record.error)
if not page.query_list:
    raise SystemExit("当前没有 SQL 执行记录")
statement_id = page.query_list[0].statement_id
detail = service.query_detail(statement_id)
if detail is not None:
    print("详情:", detail.statement_id, detail.status, detail.error)
profile = service.query_profile(statement_id)
print("画像:", profile.statement_id, profile.profile.success, profile.profile.message)
```

::::

::::{tab-item} Go
:sync: go

```go
package main

import (
	"context"
	"fmt"
	"os"

	sdk "github.com/matrixorigin/matrixflow/sdk/go-sdk"
)

func main() {
	ctx := context.Background()
	client, err := sdk.NewWithPersonalAccessToken(os.Getenv("PRODUCT_API_BASE_URL"), os.Getenv("PRODUCT_API_KEY"))
	if err != nil {
		panic(err)
	}
	workspaceID := os.Getenv("WORKSPACE_ID")
	workspace, err := client.Workspace(workspaceID)
	if err != nil {
		panic(err)
	}
	_ = workspace
	service := workspace.SQL()
	page, err := service.QueryHistory(ctx, sdk.WithQueryHistoryOffset(0), sdk.WithQueryHistoryLimit(20))
	if err != nil {
		panic(err)
	}
	fmt.Println("总数:", page.GetTotal(), "偏移:", page.GetOffset(), "数量:", page.GetLimit())
	for _, record := range page.GetQueryList() {
		fmt.Println(record.GetStatementId(), record.GetDatabase(), record.GetStatus(), record.GetError())
	}
	if len(page.GetQueryList()) == 0 {
		fmt.Println("当前没有 SQL 执行记录")
		return
	}
	statementID := page.GetQueryList()[0].GetStatementId()
	detail, err := service.QueryDetail(ctx, statementID)
	if err != nil {
		panic(err)
	}
	if detail != nil {
		fmt.Println("详情:", detail.GetStatementId(), detail.GetStatus(), detail.GetError())
	}
	profile, err := service.QueryProfile(ctx, statementID)
	if err != nil {
		panic(err)
	}
	fmt.Println("画像:", profile.GetStatementId(), profile.GetProfile().GetSuccess(), profile.GetProfile().GetMessage())
}
```

::::

:::::

(sdk-ai-studio-sql-history-limit)=
(sdk-ai-studio-sql-history-next)=
执行详情显示 SQL 的状态和错误；画像结果显示画像是否获取成功。继续查询历史时，将偏移量增加本页记录数；返回空页时结束。
